<script setup>
import {
    Position,
    Handle,
    useNode,
    useVueFlow
} from '@vue-flow/core'
import {
    ref,
    watch,
    onMounted, inject
} from "vue";
import {
    getNodeOutputFieldNames
} from '../node-def'
import {useRoute} from 'vue-router';
import {JBoltApi} from '@/service/request'
import AiKlb from '../../../../ai_knowledge_base/index.vue'

// 获取当前路由信息
const route = useRoute();
// 从路由参数中提取 appId
const appId = ref(route.params.appId);
console.log('从路由中获取appId', appId.value)


const props = defineProps(['id', 'data'])
const flow = useVueFlow();

const {
    node
} = useNode()

const klbList = ref([]);

const updateNodesData = inject("updateNodesData")
// 监听props.data的变化
watch(() => props.data, (newValue, oldValue) => {
    console.log('props.data changed ', newValue);
    updateNodesData();
}, {
    deep: true
})

const getKlbList = async () => {
    JBoltApi.tryGet('/aiKnowledgeBase/listAllEnabled', {
        appId: appId.value
    }).then(res => {
        klbList.value = res.data;
        console.log('获取知识库列表成功', res.data)
    }).catch(error => {
        console.error(error)
    });

}

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = ref([])


watch(() => flow.getEdges.value, (newV) => {
    console.debug("监听到edge改动", newV)
    updatePrevOutputFieldOptions(props.id);
})
//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV) => {
    //如果数组是空值,则清空input的值
    if (newV.length === 0) {
        // inputField.value = null;
        props.data.klbConfig.inputField = null;
    }
})
flow.onEdgesChange(events => {
    console.debug("intention init", events)
    if (events.some(item => item.type === 'remove' || item.type === 'add')) {
        prevOutputFieldOptions.value = [];
        updatePrevOutputFieldOptions(props.id);
    }
})

function updatePrevOutputFieldOptions(sourceNodeId) {
    const connections = flow.getConnectedEdges(sourceNodeId).filter(edge => edge.targetNode.id == sourceNodeId);
    console.log(connections, "connections")
    // 遍历所有前置连接
    connections.forEach(connection => {
        const sourceNode = connection.sourceNode;
        if (sourceNode) {
            // 获取该类型节点的所有输出字段名称
            const outputFields = getNodeOutputFieldNames(sourceNode.type);

            // 从sourceNode.data中获取对应字段的值
            outputFields.forEach(fieldPath => {
                // 处理嵌套字段路径，如 "llmConfig.outputField"
                const value = fieldPath.split('.').reduce((obj, key) => obj && obj[key], sourceNode
                    .data);
                if (value) {
                    if (prevOutputFieldOptions.value.some(item => item.value === value) == false) {
                        //n-select 跟 jb-seletct 的lable叫法不一样
                        // prevOutputFieldOptions.value.push({
                        //   text: value,
                        //   value: value
                        // });
                        prevOutputFieldOptions.value.push({
                            label: value,
                            value: value
                        });
                    }
                }
            });
            console.log(prevOutputFieldOptions.value, "知识库搜索的问题数组")
            updatePrevOutputFieldOptions(connection.source)

        }
    });

}

/** 获取所有前置节点的输出字段，并生成下拉选项 */
onMounted(() => {
    updatePrevOutputFieldOptions(props.id); //1.初始化的修改数组
    getKlbList();
})
</script>

<template>
    <div class="_container">
        <div class="fx fx-c_center pad-16 header">
            <div class="fx fx-center wh-40 logo">
                <jb-icon :local="true" icon="gravity-ui:database-magnifier" width="30" color="#22c55e"></jb-icon>
            </div>
            <div class="ml-10 tc-dark">
                <div>知识库搜索</div>
                <p class="font-12 tc-assist">根据文本去知识库进行检索数据</p>
            </div>
        </div>
        <div class="form fx-col pad-16 " @mousedown.stop>

            <div class="flex justify-between">
                <div class="flex items-center">
                    <span>知识库</span>&nbsp;&nbsp;
                    <n-button text size="tiny" type="primary" @click="getKlbList">
                        <template #icon>
                            <jb-icon :local="true" icon="ri:loop-right-fill"></jb-icon>
                        </template>
                    </n-button>

                </div>
                <jb-btn text
                        icon="ri:book-shelf-fill"
                        type="primary" ghost
                        size="tiny"
                        :drawerComponent="AiKlb"
                        :drawerComponentProps="{appId:appId}"
                        drawerNegativeText=""
                        drawerPositiveText=""
                        :drawerArgs="{defaultWidth: '1360px',minWidth:1360}"
                >管理
                </jb-btn>


            </div>
            <jb-select placeholder="请选择知识库" :options="klbList"
                       labelField="name" valueField="id"
                       v-model:value="props.data.klbSearchConfig.klbId"></jb-select>
            <label>问题</label>
            <n-select placeholder="请选择问题" clearable v-model:value="props.data.klbSearchConfig.inputField"
                      :options="prevOutputFieldOptions"></n-select>
            <label>查询条数</label>
            <n-input-number round style="width: 100%" :precision="0" min="0" v-model:value="props.data.klbSearchConfig.limit"
                            placeholder="请输入查询条数" max="20">
            </n-input-number>
            <label>文档相关性分值要 >= {{ props.data.klbSearchConfig.minScore }}</label>
            <div class="flex items-center">
                <n-slider v-model:value="props.data.klbSearchConfig.minScore" :step="0.1" max="1"/>
            </div>

        </div>
        <div class="footer pad-16">
            <p class="tc-gray ">输出字段</p>
            <div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
                <div class="fx fx-c_center">
                    <div class="output-flag noshrink"></div>
                    <n-input v-model:value="props.data.klbSearchConfig.outputField" placeholder="字段名"
                             class="tc-gray ml-8 w-140"></n-input>
                </div>
                <span class="tc-assist">AI生成的回答</span>
            </div>
        </div>

        <Handle type="target" :position="Position.Left"/>
        <Handle type="source" id="klb_match" :position="Position.Right"
                style="transform: translate(50%, calc(-50% - 130px))" class="handle_success"/>
        <Handle type="source" id="klb_no_match" :position="Position.Right"
                style="transform: translate(50%, calc(-50% - 50px))" class="handle_warn"/>
        <Handle type="source" id="fail" :position="Position.Right"
                style="transform: translate(50%, calc(-50% + 30px))"/>


    </div>
</template>

<style scoped>
._container {
    background-color: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-sizing: border-box;
    width: 380px;
    box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px;
}

.header,
.form {
    border-bottom: 1px solid rgb(229, 231, 235);
}

.logo {
    background: #dcfce7;
    border-radius: 12px;
}

label {
    margin-bottom: 8px;
}

label:not(:first-child) {
    margin-top: 16px;
}

.output {
    background: rgb(249, 250, 251);
    border-radius: 12px;
}

.output-flag {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #22c55e;
}
</style>
